package net.sevencolorlotus.ch01;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;

/**
 * @Description: 客户端
 * @Author: Jason.zhu
 * @Create: 2020/03/04 13:51
 */

public class EchoClient {

    private final int port;
    private final String host;

    public EchoClient(int port, String host){
        this.port = port;
        this.host = host;
    }

    /**
     * 启动客户端方法
     * @throws Exception
     */
    public void start()throws Exception{
        EventLoopGroup group = new NioEventLoopGroup();/*线程组*/
        Bootstrap b = new Bootstrap();/*客户端启动必备*/
        try {
            b.group(group)
                    .channel(NioSocketChannel.class) /*指明使用NIO进行网络通讯*/
                    .remoteAddress(new InetSocketAddress(host, port)) /*配置远程服务器的地址*/
                    .handler(new EchoClientHandler());
            ChannelFuture f = b.connect().sync();/*连接到远程节点，阻塞等待直到连接完成*/
            f.channel().closeFuture().sync();/*阻塞，直到channel关闭*/
        } finally {
            group.shutdownGracefully().sync(); //业务处理完毕线程组
        }
    }

    public static void main(String[] args) throws Exception{
        new EchoClient(9999, "127.0.0.1").start();
    }
}
